// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiResponse } from 'next';
import type { IncomingMessage } from 'http';
import formidable from 'formidable';
import * as lark from '@larksuiteoapi/node-sdk';
import fs from 'fs';
import cookie from 'cookie';
import { getLoginUser, getLoginUserByAuth } from '@/components/server/login';
type Data = {
  errno: number; // 注意：值是数字，不能是字符串
  data?: {
    /**
     * 图片 src ，必须
     */
    url: string;
    /**
     * 图片描述文字，非必须
     */
    alt?: string;
    /**
     * 图片的链接，非必须
     */
    href?: string;
  };
  message?: string; //失败信息
};
export const config = {
  api: {
    bodyParser: false,
  },
};
export default async function handler(
  req: IncomingMessage,
  res: NextApiResponse<Data>
) {
  const ret: Data = { errno: 0 };
  const cookies = cookie.parse(req.headers.cookie || '');
  const login = await getLoginUserByAuth(cookies.auth, { reqLogin: false });
  if (!login.login) {
    ret.errno = 1;
    ret.message = '用户未登录';
    res.json(ret);
    return;
  }
  const form = formidable({});
  const [fields, files] = await form.parse(req);
  const file = files['wangeditor-uploaded-image'];
  console.log(files);
  if (!file) {
    ret.errno = 1;
    ret.message = '没有上传文件';
    res.json(ret);
    return;
  }
  const client = new lark.Client({
    appId: process.env.feishu_appid || '',
    appSecret: process.env.eishu_appkey || '',
  });
  await client.drive.v1.file
    .uploadAll({
      data: {
        file_name: file[0]['originalFilename'] || '',
        parent_type: 'explorer',
        parent_node: 'XSL7f5rHvlDgkidGR2acnmIQnHc',
        size: file[0]['size'] || 0,
        file: fs.createReadStream(file[0]['filepath']),
      },
    })
    .then((res) => {
      ret.data = {
        url: '/api/view/' + res?.file_token,
        alt: file[0]['originalFilename'] || '',
        href: '',
      };
      console.log(res);
    })
    .catch((e) => {
      ret.errno = 1;
      ret.message = e;
    });
  res.status(200).json(ret);
}
